# -*- coding: utf-8 -*-

import json

from django.utils.decorators import method_decorator
from django.views.generic import TemplateView

from common.console import db
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.tz import utc_to_local_str

_LOGGER = track_logging.getLogger(__name__)


class RoleView(TemplateView):
    @method_decorator(token_required)
    def get(self, req, *args, **kwargs):
        query_dct = req.GET.dict()
        items, total_count = db.list_roles(query_dct, req.user.role)
        resp_items = []
        for item in items:
            data = item.as_dict()
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['permission'] = data.pop('permissions').split(',')
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(RoleView, self).dispatch(*args, **kwargs)


class SingleRoleView(TemplateView):
    def get(self, req, role_id):
        role_id = int(role_id)
        return db.get_role(role_id).as_dict()

    def post(self, req, role_id):
        return self.put(req, role_id)

    def put(self, req, role_id):
        role_id = int(role_id)
        query_dct = json.loads(req.body)
        db.update_role(role_id, query_dct.get('rolename'), query_dct.get('permission'))
        return {}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleRoleView, self).dispatch(*args, **kwargs)
